package com.partners.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.partners.configure.wechatmp.WxMpProperties;
import com.partners.constant.ErrorMessageEnum;
import com.partners.dao.dto.ExchangeInputDTO;
import com.partners.dao.dto.TemplateDTO;
import com.partners.dao.basic.PointProductDao;
import com.partners.dao.basic.ProductExchangeDao;
import com.partners.dao.basic.UserDao;
import com.partners.dao.bo.PointProductDO;
import com.partners.dao.bo.ProductExchangeDO;
import com.partners.dao.bo.UserDO;
import com.partners.model.BusinessException;
import com.partners.model.Paging;
import com.partners.service.ExchangeService;
import com.partners.service.TemplateService;
import com.partners.service.UploadFileService;
import com.partners.utils.CodeUtils;
import com.partners.utils.TimestampUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liangyongle
 * @date 2018-12-28
 */
@Service
@Slf4j
public class ExchangeServiceImpl implements ExchangeService{

    @Resource
    private ProductExchangeDao productExchangeDao;

    @Resource
    private PointProductDao pointProductDao;

    @Resource
    private UserDao userDao;

    @Resource
    private TemplateService templateServcie;

    @Resource
    private UploadFileService uploadFileService;


    @Resource
    private WxMpProperties wxMpProperties;


    /**
     *获取兑换列表
     * @param  paging Paging
     * return list
     * */
    @Override
    public Map<String, Object> getExchangeList(Paging paging, Integer orderNo) {
        PageHelper.startPage(paging.getPage(),paging.getRows());
        Map<String,Object> allList = new HashMap<>();
        Integer nowtime = TimestampUtils.timestamp();
        List<Map<String,Object>> list =  productExchangeDao.getExchangeList(orderNo);
        for (Map<String,Object> map:list){
            String timeFormat = "yyyy-MM";
            String addtime = TimestampUtils.getDateTimeOfTimestamp((Integer) map.get("addtime"),timeFormat);
            map.put("addtime",addtime);
        }
        PageInfo page = new PageInfo(list);
        Object total = page.getTotal();
        allList.put("total",total);
        allList.put("list",list);
        return allList;
    }


    /**
     *用户-获取用户的兑换列表
     * @param  paging Paging uid Integer
     * return list
     * */
    @Override
    public Map<String, Object> getUserExchangeList(Paging paging, Integer uid) {
        PageHelper.startPage(paging.getPage(),paging.getRows());
        Map<String,Object> allList = new HashMap<>();
        Integer nowtime = TimestampUtils.timestamp();
        List<Map<String,Object>> list =  productExchangeDao.getUserExchangeList(uid);
        for (Map<String,Object> map:list){
            String timeFormat = "yyyy-MM";
            String addtime = TimestampUtils.getDateTimeOfTimestamp((Integer) map.get("addtime"),timeFormat);
            map.put("addtime",addtime);
        }
        PageInfo page = new PageInfo(list);
        Object total = page.getTotal();
        allList.put("total",total);
        allList.put("list",list);
        return allList;
    }

    /**
     *选择产品兑换
     * @param  exchangeInputDTO ExchangeInputDTO
     * return list
     * */
    @Override
    @Transactional
    public Integer exchangeProduct(ExchangeInputDTO exchangeInputDTO) {
        //1.查询当前用户是否被禁用
        //2.查询当前产品是否下架
        //3.查询当前产品的库存是否足够
        //4.查询当前用户的积分是否足够兑换
        //5.扣除产品的库存
        //6.兑换产品，更新产品兑换数，扣除用户的积分
        //7.如果是门店中自提的需要新增核销二维码
        UserDO user = userDao.selectByPrimaryKey(exchangeInputDTO.getUid());
        if(user.getEnable() ==1){
           throw BusinessException.of(ErrorMessageEnum.HANDLE_NOT_FOUNT);
        }
        PointProductDO pointProduct = pointProductDao.selectByPrimaryKey(exchangeInputDTO.getProductId());
        if(pointProduct.getIsup() ==1){
           throw BusinessException.of(ErrorMessageEnum.PRODUCT_IS_DOWN);
        }
        if(pointProduct.getStock() ==0){
           throw  BusinessException.of(ErrorMessageEnum.STOCK_NOT_ENOUGH);
        }
        log.info("userPoint:{},points:{}",user.getBalance(),pointProduct.getPoint());
        if(user.getBalance() < pointProduct.getPoint()){
           throw BusinessException.of(ErrorMessageEnum.POINT_NOT_ENOUGH);
        }
        ProductExchangeDO productExchange = new ProductExchangeDO();
        //生成新的兑换单号
        Long orderNo = CodeUtils.createExchangeNum();
        //写入日志记录表
        productExchange.setOrderNo(orderNo);
        productExchange.setUid(exchangeInputDTO.getUid());
        productExchange.setProductId(exchangeInputDTO.getProductId());
        productExchange.setType(exchangeInputDTO.getType().byteValue());
        productExchange.setTitle(pointProduct.getTitle());
        productExchange.setPic(pointProduct.getPic());
        productExchange.setName(exchangeInputDTO.getName());
        productExchange.setPhone(exchangeInputDTO.getPhone());
        productExchange.setAddress(exchangeInputDTO.getAddress());
        productExchange.setPoint(pointProduct.getPoint());
        productExchange.setAddtime(TimestampUtils.timestamp());
        productExchangeDao.insertSelective(productExchange);

        //如果是门店自提的需要生成核销二维码
        if(exchangeInputDTO.getType() == 0){
            //更新二维码
            String baseUrl = wxMpProperties.getBaseUrl();
            String url =baseUrl+"/pointsPage/verify?id"+productExchange.getId();
            log.info("url：{}",url);
            String qrcode = uploadFileService.createQrcode(url);
            ProductExchangeDO productExchangeDO = new ProductExchangeDO();
            productExchangeDO.setId(productExchange.getId());
            productExchangeDO.setVerifyCode(qrcode);
            productExchangeDao.updateByPrimaryKeySelective(productExchangeDO);
        }

        //扣除产品的库存并增加兑换数
        PointProductDO productDO = new PointProductDO();
        productDO.setId(exchangeInputDTO.getProductId());
        productDO.setStock(pointProduct.getStock()-1);
        productDO.setExchange(pointProduct.getExchange()+1);
        pointProductDao.updateByPrimaryKeySelective(productDO);
        //扣除用户的积分
        UserDO userDO = new UserDO();
        userDO.setId(exchangeInputDTO.getUid());
        userDO.setBalance(user.getBalance()-pointProduct.getPoint());
        userDao.updateByPrimaryKeySelective(userDO);
        //发送模板消息通知
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date nowTime = new Date(System.currentTimeMillis());
        TemplateDTO templateDTO = new TemplateDTO();
        templateDTO.setFirst("兑换成功");
        templateDTO.setKeyword1("您已经花费"+pointProduct.getPoint()+"积分成功兑换了"+pointProduct.getTitle());
        templateDTO.setKeyword2(format.format(nowTime));
        templateDTO.setRemark("");
        templateServcie.sendHanleTemplate(templateDTO,user.getOpenid());
        return 1;
    }


    /**
     * 发货或者核销
     * @Param
     * return Boolean
     * */
    @Override
    @Transactional
    public Map<String,Object> sendVerifyExchange(Integer id,Integer uid) {

        Map<String,Object> result = new HashMap<>();
       //1.查询当前记录是否存在
       //2.查询当前记录是否已经发货了或者核销，或者已收货
        ProductExchangeDO productExchangeDO = productExchangeDao.selectByPrimaryKey(id);
        if(productExchangeDO == null){
            result.put("code",-100017);
            result.put("msg","记录不存在");
            return result;
            //throw BusinessException.of(ErrorMessageEnum.RECORD_NOT_FOUND);
        }
        if(productExchangeDO.getStatus() >0){
            result.put("code",-100061);
            result.put("msg","不在核销或者发货状态");
            return result;
            //throw BusinessException.of(ErrorMessageEnum.EXCHANGE_IS_OVER);
        }
        Byte status = 1;
        ProductExchangeDO productExchange = new ProductExchangeDO();
        productExchange.setId(id);
        productExchange.setStatus(status);
        productExchange.setVerifyId(uid);
        productExchange.setVerifyTime(TimestampUtils.timestamp());
        productExchangeDao.updateByPrimaryKeySelective(productExchange);
        //发送模板消息通知
        //查询产品标题
        PointProductDO pointProductDO = pointProductDao.selectByPrimaryKey(productExchangeDO.getProductId());
        //查询openid
        UserDO userDO = userDao.selectByPrimaryKey(productExchangeDO.getUid());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date nowTime = new Date(System.currentTimeMillis());
        TemplateDTO templateDTO = new TemplateDTO();
        if(productExchangeDO.getType() == 1){
            templateDTO.setFirst("奖品发货通知");
            templateDTO.setKeyword1("您兑换的"+pointProductDO.getTitle()+"产品已发货");
        }else{
            templateDTO.setFirst("奖品领取成功");
            templateDTO.setKeyword1("您兑换的"+pointProductDO.getTitle()+"产品已领取成功");
        }
        templateDTO.setKeyword2(format.format(nowTime));
        templateDTO.setRemark("");
        templateServcie.sendHanleTemplate(templateDTO,userDO.getOpenid());
        result.put("code",200);
        result.put("msg","核销成功");
        return result;
    }




    /**
     * 收货
     * @Param id Integer
     * return Boolean
     * */
    @Override
    public void finishExchange(Integer id) {
        ProductExchangeDO productExchangeDO = productExchangeDao.selectByPrimaryKey(id);
        if(productExchangeDO == null){
            throw BusinessException.of(ErrorMessageEnum.RECORD_NOT_FOUND);
        }
        if(productExchangeDO.getStatus() == 2){
            throw BusinessException.of(ErrorMessageEnum.EXCHANGE_IS_FINISH);
        }
        Byte status = 2;
        ProductExchangeDO productExchange = new ProductExchangeDO();
        productExchange.setId(id);
        productExchange.setStatus(status);
        productExchange.setFinishTime(TimestampUtils.timestamp());
        productExchangeDao.updateByPrimaryKeySelective(productExchange);
    }

}
